package com.yingpai.fitness.dvp_2_0.main.activity.fitness;

import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.DisplayMetrics;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.lzy.okgo.model.Response;
import com.yingpai.fitness.R;
import com.yingpai.fitness.adpter.course.CourseDetailVideoRecyclerAdapter;
import com.yingpai.fitness.dvp_2_0.common.activity.CommonActivity;
import com.yingpai.fitness.dvp_2_0.common.adapter.BaseAdapterHelper;
import com.yingpai.fitness.dvp_2_0.common.adapter.QuickAdapter;
import com.yingpai.fitness.dvp_2_0.common.finalokgo.callback.Callback;
import com.yingpai.fitness.dvp_2_0.common.finalokgo.request.RequestType;
import com.yingpai.fitness.dvp_2_0.common.util.constant.Contacts;
import com.yingpai.fitness.dvp_2_0.main.activity.shop.ShopDetailActivity;
import com.yingpai.fitness.dvp_2_0.main.util.constant.Constant;
import com.yingpai.fitness.entity.RunStrategyBean;
import com.yingpai.fitness.dvp_2_0.main.widget.CustomLinearLayoutManager;
import com.yingpai.fitness.dvp_2_0.main.widget.ParentRecyclerView;
import com.yingpai.fitness.dvp_2_0.main.widget.RecyclerViewDivider;
import com.yingpai.fitness.dvp_2_0.common.view.XGridView;
import com.zzhoujay.richtext.RichText;

import java.text.DecimalFormat;

import butterknife.BindView;
import butterknife.OnClick;
import cn.jzvd.JZVideoPlayer;

public class RunStrategyActivity extends CommonActivity {


    @BindView(R.id.runknowledgeDetailWb)
    TextView runknowledgeDetailWb;
    @BindView(R.id.gridview_equip)
    XGridView gridviewEquip;
    @BindView(R.id.gridview_food)
    XGridView gridviewFood;
    @BindView(R.id.run_strategy_video_parent_rv_list)
    ParentRecyclerView runStrategyVideoParentRvList;
    private CourseDetailVideoRecyclerAdapter videoRecyclerAdapter;
    private String url;
    private QuickAdapter<RunStrategyBean.MapBean.MerchandiseListBean> equip_adapter;
    private QuickAdapter<RunStrategyBean.MapBean.DietDetailListBean> food_adapter;
    SensorManager sensorManager;
    JZVideoPlayer.JZAutoFullscreenListener sensorEventListener;
    private DecimalFormat df = new DecimalFormat("######.###");


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStatusFlag(Contacts.NORMAL_STATUS);
        setContentView(R.layout.run_strategy_activity);
    }


    @Override
    protected void initData() {
        showDialog(this,null);
        finalOkGo.request(RequestType.GET, Contacts.HOST_SERVER + url, null, url, new Callback<RunStrategyBean>() {
            @Override
            public void onSuccess(RunStrategyBean runStrategyBean) {
                if (Constant.REQUEST_SUCCESS.equals(runStrategyBean.getResult())) {

                    setTitle(runStrategyBean.getMap().getStrategy().getTitleName());
                    RichText.fromHtml(runStrategyBean.getMap().getStrategy().getContent()).into(runknowledgeDetailWb);

                    int size = runStrategyBean.getMap().getMerchandiseList().size();
                    int length = 119;
                    DisplayMetrics dm = new DisplayMetrics();
                    getWindowManager().getDefaultDisplay().getMetrics(dm);
                    float density = dm.density;
                    int gridviewWidth = (int) (size * (length + 4) * density);
                    int itemWidth = (int) (length * density);

                    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                            gridviewWidth, LinearLayout.LayoutParams.FILL_PARENT);
                    gridviewEquip.setLayoutParams(params); // 设置GirdView布局参数,横向布局的关键
                    gridviewEquip.setColumnWidth(itemWidth); // 设置列表项宽
                    gridviewEquip.setHorizontalSpacing(4); // 设置列表项水平间距
                    gridviewEquip.setStretchMode(GridView.NO_STRETCH);
                    gridviewEquip.setNumColumns(size); // 设置列数量=列表集合数

                    int size1 = runStrategyBean.getMap().getDietDetailList().size();
                    int length1 = 119;
                    DisplayMetrics dm1 = new DisplayMetrics();
                    getWindowManager().getDefaultDisplay().getMetrics(dm1);
                    float density1 = dm1.density;
                    int gridviewWidth1 = (int) (size1 * (length1 + 4) * density1);
                    int itemWidth1 = (int) (length1 * density1);

                    LinearLayout.LayoutParams params1 = new LinearLayout.LayoutParams(
                            gridviewWidth1, LinearLayout.LayoutParams.FILL_PARENT);
                    gridviewFood.setLayoutParams(params1); // 设置GirdView布局参数,横向布局的关键
                    gridviewFood.setColumnWidth(itemWidth1); // 设置列表项宽
                    gridviewFood.setHorizontalSpacing(4); // 设置列表项水平间距
                    gridviewFood.setStretchMode(GridView.NO_STRETCH);
                    gridviewFood.setNumColumns(size1); // 设置列数量=列表集合数

                    equip_adapter.clear();
                    equip_adapter.addAll(runStrategyBean.getMap().getMerchandiseList());
                    equip_adapter.notifyDataSetChanged();

                    food_adapter.clear();
                    food_adapter.addAll(runStrategyBean.getMap().getDietDetailList());
                    food_adapter.notifyDataSetChanged();

                    videoRecyclerAdapter.setNewData(runStrategyBean.getMap().getVideos());
                    videoRecyclerAdapter.notifyDataSetChanged();
                } else {
                    showToast(runStrategyBean.getMsg() + "");
                }
                dismissDialog();
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
                dismissDialog();
            }
        });
    }


    @Override
    public void onPointerCaptureChanged(boolean hasCapture) {

    }

    @Override
    public void onBackPressed() {
        if (JZVideoPlayer.backPress()) {
            return;
        }
        super.onBackPressed();
    }

    @Override
    protected void onResume() {
        super.onResume();
        Sensor accelerometerSensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        sensorManager.registerListener(sensorEventListener, accelerometerSensor, SensorManager.SENSOR_DELAY_NORMAL);
    }

    @Override
    protected void initView() {
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            url = bundle.getString("linkurl");
        }

        equip_adapter = new QuickAdapter<RunStrategyBean.MapBean.MerchandiseListBean>(this, R.layout.item_run_strategy) {
            @Override
            protected void convert(BaseAdapterHelper helper, RunStrategyBean.MapBean.MerchandiseListBean item) {
                ImageView photo = helper.getView(R.id.photo);
                Glide.with(context)
                        .load(item.getPhotoUrls())
                        .placeholder(R.mipmap.default_big_bg)
                        .into(photo);
                helper.setText(R.id.title, item.getMerchandiseName());
                helper.setText(R.id.price, "￥" + df.format(item.getCommonPrice() / 100));
                helper.setText(R.id.member_price, "会员价￥" + df.format(item.getMemberPrice() / 100));
            }
        };

        gridviewEquip.setAdapter(equip_adapter);

        food_adapter = new QuickAdapter<RunStrategyBean.MapBean.DietDetailListBean>(this, R.layout.item_run_strategy) {
            @Override
            protected void convert(BaseAdapterHelper helper, RunStrategyBean.MapBean.DietDetailListBean item) {
                ImageView photo = helper.getView(R.id.photo);
                Glide.with(context)
                        .load(item.getPhotoUrl())
                        .placeholder(R.mipmap.default_big_bg)
                        .into(photo);
                helper.setText(R.id.title, item.getDietName());
                helper.setText(R.id.price, "￥" + df.format(item.getCommonPrice() / 100));
                helper.setText(R.id.member_price, "会员价￥" + df.format(item.getMemberPrice() / 100));
            }
        };

        gridviewFood.setAdapter(food_adapter);

        runStrategyVideoParentRvList.setLayoutManager(new CustomLinearLayoutManager(getApplicationContext()));
        videoRecyclerAdapter = new CourseDetailVideoRecyclerAdapter(R.layout.item_run_strategy_video, this);
        runStrategyVideoParentRvList.addItemDecoration(new RecyclerViewDivider(getApplicationContext(), LinearLayoutManager.HORIZONTAL,
                16, getApplicationContext().getResources().getColor(R.color.line_color_gray_dark)));
        runStrategyVideoParentRvList.setAdapter(videoRecyclerAdapter);

        gridviewEquip.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Bundle bundle1 = new Bundle();
                bundle1.putInt("id", equip_adapter.getItem(position).getId());
                startActivity(ShopDetailActivity.class, bundle1);
            }
        });

        gridviewFood.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Bundle bundle1 = new Bundle();
                bundle1.putInt("id", food_adapter.getItem(position).getId());
                startActivity(DieCollocationDetailActivity.class, bundle1);
            }
        });

        runStrategyVideoParentRvList.addOnChildAttachStateChangeListener(new RecyclerView.OnChildAttachStateChangeListener() {
            @Override
            public void onChildViewAttachedToWindow(View view) {
                JZVideoPlayer.onChildViewAttachedToWindow(view, R.id.video);
            }

            @Override
            public void onChildViewDetachedFromWindow(View view) {
                JZVideoPlayer.onChildViewDetachedFromWindow(view);
            }
        });

        sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
        sensorEventListener = new JZVideoPlayer.JZAutoFullscreenListener();
    }

    @Override
    protected void onPause() {
        super.onPause();
        sensorManager.unregisterListener(sensorEventListener);
        JZVideoPlayer.releaseAllVideos();
    }

    @Override
    @OnClick({})
    public void onViewClicked(View view) {
        super.onViewClicked(view);
        switch (view.getId()) {

        }
    }
}
